package com.yueshop.yueshopsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.yueshop.common.to.SkuEsModel;
import com.yueshop.yueshopsearch.constant.EsConstant;
import com.yueshop.yueshopsearch.service.ShopSearchService;
import com.yueshop.yueshopsearch.vo.SearchParam;
import com.yueshop.yueshopsearch.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShopSearchServiceImpl implements ShopSearchService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchResult searchResult =null;
        //1.准备检索请求
        SearchRequest  searchRequest = buildSearchRqeuset(searchParam);
        //2.执行检索
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //3.分析响应的数据
            searchResult =bulidSearchResult(searchResponse,searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    /**
     * 准备检索方法
     * 模糊匹配,过滤(属性id 分类 品牌 价格区间 库存) 排序 分页 高亮 聚合分析
     */
    private SearchRequest buildSearchRqeuset(SearchParam searchParam) {
        //构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        /**
         * 一.模糊匹配,过滤(属性id 分类 品牌 价格区间 库存)
         */
        //1 构建bool查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1.1 must 模糊匹配
        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
        //1.2 filter 过滤的内容 三级分类id
        if(searchParam.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }
        //1.3 filter 品牌id
        if(searchParam.getBrandId()!=null&&searchParam.getBrandId().size()>0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        //1.4 filter 是否库存
        if(searchParam.getHasStock()!=null){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("hasStock",searchParam.getHasStock()==1));
        }
        //1.5 filter 价格区间  1_500/1_/_500
        if(!StringUtils.isEmpty(searchParam.getSkuPrice())){
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            // 1_500/1_/_500
            String[] s = searchParam.getSkuPrice().split("_");
            if(s.length==2){ //1_500  _500
                if(searchParam.getSkuPrice().startsWith("_")){
                    rangeQueryBuilder.lte(Double.parseDouble(s[1]));
                }else{//1_500
                    rangeQueryBuilder.lte(Double.parseDouble(s[1])).gte(Double.parseDouble(s[0]));
                }
            }else if(s.length==1){//1_
                rangeQueryBuilder.gte(Double.parseDouble(s[0]));
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        //1.6 filter 属性检索 attrs=1_安卓:ios:其他
        if(searchParam.getAttrs()!=null&&searchParam.getAttrs().size()>0){


            for (String attr:searchParam.getAttrs()){
                BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
                //构建查询语句 每一个attr都需要生成一个完成的nested查询
                String[] s = attr.split("_");
                String attrId = s[0];//检索属性的id
                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrId",attrId));
                //构建属性值查询
                String[] arrtValues = s[1].split(":");
                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",arrtValues));

                NestedQueryBuilder attrs = QueryBuilders.nestedQuery("attrs", queryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(attrs);
            }
        }
        //封装了上述查询
        sourceBuilder.query(boolQueryBuilder);

        /**
         * 二. 排序 分页 高亮
         */
        //2.1 排序
        // sort=saleCount_asc/desc
        if(!StringUtils.isEmpty(searchParam.getSort())){
            String[] s = searchParam.getSort().split("_");
            SortOrder sortOrder=s[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC;
            sourceBuilder.sort(s[0], sortOrder);
        }
        //2.2分页
        sourceBuilder.from((searchParam.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE); //(当前页-1)*每页显示条数
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //2.3高亮
        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            highlightBuilder.field("skuTitle");
            sourceBuilder.highlighter(highlightBuilder);
        }




        /**
         * 聚合分析
         */
        //3.1品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(20);
        //聚合品牌名称
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        //聚合品牌图片
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);

        //3.2 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);

        //3.3 属性聚合
        //声明嵌入式的聚合
        NestedAggregationBuilder attrs_agg = AggregationBuilders.nested("attrs_agg", "attrs");
        //通过属性id 聚合出所有属性
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(20);
        //属性id子聚合 聚合出属性名
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //属性id子聚合 聚合出属性值
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(20));
        attrs_agg.subAggregation(attr_id_agg);

        sourceBuilder.aggregation(attrs_agg);




        System.out.println("DSL语句:"+sourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }



    /**
     * 构建响应数据的方法
     * @param searchResponse
     * @return
     */
    private SearchResult bulidSearchResult(SearchResponse searchResponse,SearchParam searchParam) {

        SearchResult searchResult = new SearchResult();
        SearchHits hits = searchResponse.getHits();
        //1.封装所有的商品信息
        List<SkuEsModel> prdoucts = new ArrayList<>();

        for (SearchHit hit : hits.getHits()) {
            String json = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(json, SkuEsModel.class);
            if(!StringUtils.isEmpty(searchParam.getKeyword())){
                HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                skuEsModel.setSkuTitle(skuTitle.fragments()[0].string())  ;
            }
            prdoucts.add(skuEsModel);
        }


        searchResult.setProducts(prdoucts);
        //2. 封装所有商品涉及的分类信息
        List<SearchResult.CatalogVo> catalogVos= new ArrayList<>();
        ParsedLongTerms catalog_agg = searchResponse.getAggregations().get("catalog_agg");

        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //获取分类id
            String catalogId = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(catalogId));

            //获取分类名称
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }


        searchResult.setCatalogs(catalogVos);
        //3.封装所有商品涉及的品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //获取品牌id
            String brandId = bucket.getKeyAsString();
            brandVo.setBrandId(Long.parseLong(brandId));
            //获取品牌名称
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brand_name = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brand_name);
            //获取品牌图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brand_img = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brand_img);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);
        //4.封装所有商品涉及的属性
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrs_agg = searchResponse.getAggregations().get("attrs_agg");
        ParsedLongTerms attr_id_agg = attrs_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //1.获取属性id
            long arrtId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(arrtId);
            //2.获取属性名称
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String arrt_name = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(arrt_name);
            //3.获取属性值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attr_value_agg.getBuckets().stream().map(item -> {
                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());

            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }

        searchResult.setAttrs(attrVos);



        //5.分页 当前页码
        searchResult.setPageNum(searchParam.getPageNum());
        //6.命中总数
        long total =  hits.getTotalHits().value;
        searchResult.setTotal(total);
        //7.总页面数
        int totalPages = total%EsConstant.PRODUCT_PAGESIZE==0?(int)total/EsConstant.PRODUCT_PAGESIZE:(int)total/EsConstant.PRODUCT_PAGESIZE+1;
        searchResult.setTotalPages(totalPages);

        //8.设置导航页码
        List<Integer> pageNav = new ArrayList<>();
        for (int i=1;i<=totalPages;i++) {
            pageNav.add(i);
        }
        searchResult.setPageNavs(pageNav);
        return searchResult;
    }


}
